<?php
/**
 * Created by PhpStorm.
 * User: Lsen
 * Date: 2018/4/19
 * Time: 13:50
 */
//订单管理控制器
namespace app\admin\controller;

use app\api\model\Order as OrderModel;
use app\api\service\Car as CarInterface;
use app\lib\enum\CarActionEnum;
use think\Config;
use think\Db;
use think\Exception;
use WeMini\Newtmpl;

class Order extends Common
{
    public function index()
    {
        $map = [];
        // $map['o.company_id'] = ['<>', 45];
        $data = [
            'vehicle_id' => '',
            'order_status' => '',
            'company_id' => '',
            'zt' => ''
        ];
        //页码
        $pageNum = 1;
        if (request()->isPost()){
            $data = input('post.');
            if (!empty($data['vehicle_id'])) {
                $map['o.vehicle_id'] = $data['vehicle_id'];
            }
            if (!empty($data['mobile'])) {
                $map['o.mobile'] = ['like', "%{$data['mobile']}%"];
            }
            if ($data['order_status'] != '') {
                $map['o.order_status'] = $data['order_status'];
            } else {
                $map['o.order_status'] = ['in', '0,2,3,4'];
            }
            if ($data['zt'] != '') {
                if ($data['zt'] == 0 || $data['zt'] == 1) {
                    $map['o.zt'] = ['in', '0,1'];
                } else {
                    $map['o.zt'] = $data['zt'];
                }
            }
            if ($data['user_name'] != '') {
                $map['d.user_name'] = ['like', "%{$data['user_name']}%"];
            }
            if (!empty($data['license_number'])) {
                $map['d.license_number'] = ['like', "%{$data['license_number']}%"];
            }
            if (!$data['order_sn'] == '') {
                if (strlen($data['order_sn']) == 23) {
                    $map['o.order_sn'] = $data['order_sn'];
                } else {
                    $map['o.order_sn'] = ['like', "%{$data['order_sn']}%"];
                }
            }
            if (!empty($data['company_id'])) {
                if($data['company_id'] != 45){
                    $map['o.company_id'] = $data['company_id'];
                }else{
                    $map['o.company_id'] = 45;
                }
            }
            if (!empty($data['start_time']) && !empty($data['end_time'])) {
                $map['o.create_time'] = ['between', [strtotime($data['start_time']), strtotime($data['end_time']) + 86399]];
            } elseif (!empty($data['start_time']) && empty($data['end_time'])) {
                $map['o.create_time'] = ['between', [strtotime($data['start_time']), time()]];
            } elseif (empty($data['start_time']) && !empty($data['end_time'])) {
                $map['o.create_time'] = ['between', [0, strtotime($data['end_time']) + 86399]];
            }
            if (!empty($data['subscribe_date'])) {
                $map['o.subscribe_date'] = ['between', [strtotime($data['subscribe_date']), strtotime($data['subscribe_date']) + 86399]];
            }
            if (is_numeric(input('post.pageNum'))) {
                $pageNum = input('post.pageNum');
            }
        }
        $data['pageNum'] = $pageNum;
        //每页数量
        $numPerPage = config('num_per_page');
        $data['numPerPage'] = $numPerPage;
        //列表数据
        $model = new \app\admin\model\Order();
        $data['list'] = $model->get_list($map, $pageNum, $numPerPage, '');
        $data['count'] = $model->get_list($map, '', '', 1);
        $data['vehicle'] = db('vehicle')->select();
        $data['company'] = db('company')->field('id, company_name')->where('is_delete', 0)->where('is_use', 1)->select();
        return view('', $data);
    }

    /**
     *订单详情
     */
    public function detail()
    {
        $data = [];
        $order_id = input('get.id');
        $order = db('order')->where('order_id', $order_id)->find();
        $order['nick_name'] = db('user_weixin')->where('id', '=', $order['user_weixin_id'])->value('nick_name');
        $map['user_weixin_id'] = $order['user_weixin_id'];
        $map['id'] = $order['driving_license_id'];
        $dl_info = get_info('driving_license', $map, '');
        if (empty($dl_info['image_id'])) {
            $dl_info['license_image'] = 'no-driving.png';
        } else {
            $dl_info['license_image'] = db('image')->where('id', '=', $dl_info['image_id'])->value('url');
        }
        $dl_info['license_image'] = Config::get('mp_image_url') . $dl_info['license_image'];
        $data['order_info'] = $order;
        $data['dl_info'] = $dl_info;
        return view('', $data);
    }

    public function refresh()
    {
        $lsh = input('get.lsh');
        $data = json_encode(['lsh' => $lsh], JSON_UNESCAPED_UNICODE);
        $param = [
            'action' => CarActionEnum::CHECK_SUBSCRIBE,
            'data'   => $data,
        ];
        $res = '';
        try {
            $car = new CarInterface($param);
            $result = $car->appointment();
            if (1 == $result['code']) {
                $res = json_decode($result['data'], true);
                OrderModel::update(['zt' => $res['zt']], ['lsh' => $lsh]);
                // if(-2 == $res['zt']){
                //     $config = Config::get('wechat');
                //     $mini = new Newtmpl($config);
                //     $data = $this->generateAuditNoticeData('failed', $lsh, $config);
                //     $mini->send($data);
                // }
            }
        } catch (Exception $e) {
            return json([
                'statusCode' => 300,
                'message'    => $e->getMessage(),
            ]);
        }
        return json([
            'statusCode' => 200,
            'message'    => '刷新状态成功',
            'navTabId'   => 'OrderManage',
            'data'       => $res,
        ]);
    }

    public function refresh2()
    {
        $lsh = input('get.lsh');
        $data = json_encode(['lsh' => $lsh], JSON_UNESCAPED_UNICODE);
        $param = [
            'action' => CarActionEnum::CHECK_SUBSCRIBE,
            'data'   => $data,
        ];
        $res = '';
        try {
            $car = new CarInterface($param);
            $result = $car->appointment();
            if (1 == $result['code']) {
                $res = json_decode($result['data'], true);
                OrderModel::update(['zt' => $res['zt']], ['lsh' => $lsh]);
                if(-2 == $res['zt']){
                    $config = Config::get('wechat');
                    $mini = new Newtmpl($config);
                    $data = $this->generateAuditNoticeData('failed', $lsh, $config);
                    $mini->send($data);
                }
            }
        } catch (Exception $e) {
            return json([
                'statusCode' => 300,
                'message'    => $e->getMessage(),
            ]);
        }
        return json([
            'statusCode' => 200,
            'message'    => '刷新状态成功',
            'navTabId'   => 'OrderManage',
            'data'       => $res,
        ]);
    }

    private function generateAuditNoticeData($type, $lsh, $config, $tmplId = 'auditNotice')
    {
        $phrase1 = $thing3 = '';
        switch ($type) {
            case 'subscribeWaitAudit':
                $phrase1 = '待审核';
                $thing3 = '请刷新状态，显示预约成功后方可检车';
                break;
            case 'subscribeAuditing':
                $phrase1 = '审核中';
                $thing3 = '请刷新状态，显示预约成功后方可检车';
                break;
            case 'failed':
                $phrase1 = '审核未通过';
                $thing3 = '请用相同手机号和车牌号重新预约';
                break;
        }
        $order = Db::name('order')->where('lsh', '=', $lsh)->find();
        $data = [
            'character_string4' => ['value' => $order['order_sn']], // 订单编号
            'phrase1'           => ['value' => $phrase1], // 审核状态
            'date2'             => ['value' => date('Y-m-d H:i:s', $order['update_time'])], // 审核时间
            'thing5'            => ['value' => '无'], // 未通过原因
            'thing3'            => ['value' => $thing3], // 备注
        ];
        return [
            'touser'            => $order['open_id'],
            'template_id'       => $config[$tmplId],
            'page'              => '/pages/order-detail/order-detail?id=' . $order['order_id'],
            'data'              => $data,
            'miniprogram_state' => 'formal',
            'lang'              => 'zh_CN',
        ];
    }
}